import axios from 'axios'
import store from '@/store'
import { getToken } from './auth'
import { ElMessage, ElLoading } from 'element-plus'

const baseUrl = process.env.VUE_APP_BASE_API
const service = axios.create({
  baseURL: baseUrl,
  headers: {
    'Content-Type': 'application/json',
    'withCredentials': true
  },
  timeout: 10000

})

let loading = null
const duration = 5
const processType = process.env.NODE_ENV

// 请求拦截器
service.interceptors.request.use(config => {
  const { showLoading } = config['tipsConfig']
  if (store.getters.token) {
    config.headers['Authorization'] = 'Bearer ' + getToken()
  }
  if (showLoading) {
    loading = ElLoading.service({
      text: 'Loading...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }

  return config
}, error => {
  loading && loading.close()
  ElMessage({
    message: '请求错误！',
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
})

// 返回内容拦截
service.interceptors.response.use(response => {
  loading && loading.close()
  const { config, data } = response
  const { showSuccessMsg, showFailMsg } = config['tipsConfig']
  processType === 'development' && console.log({ response })
  if (config.responseType === 'blob') {
    return response
  }
  const { code, message } = data
  if (code === 20000 && showSuccessMsg) {
    ElMessage({
      message: message || '处理成功',
      type: 'success',
      duration: duration * 1000
    })
  } else if (code === 10004 && showFailMsg) {
    ElMessage({
      message: '登录信息失效，请重新登录！',
      type: 'error',
      duration: duration * 1000
    })
  } else if (showFailMsg) {
    ElMessage({
      message: data.message || '系统繁忙！',
      type: 'error',
      duration: duration * 1000
    })
  }

  return data
}, error => {
  loading && loading.close()
  // 处理网络请求失败
  if (error.response) {
    switch (error.response.status) {
      case 404:
        ElMessage({
          message: '服务器未知故障！',
          type: 'error',
          duration: 5 * 1000
        })
        break
      case 401:
        // store.dispatch('user/resetToken').then(() => {
        //   location.reload()
        // })
        ElMessage({
          message: '登录已过期,请重新登录！',
          type: 'error',
          duration: 5 * 1000
        })
        break
      case 500:
        ElMessage({
          message: '服务器错误！',
          type: 'error',
          duration: 5 * 1000
        })
        break
      case 503:
        ElMessage({
          message: '服务器繁忙！',
          type: 'error',
          duration: 5 * 1000
        })
        break
      default:
        ElMessage({
          message: '系统繁忙！',
          type: 'error',
          duration: 5 * 1000
        })
    }
  } else {
    ElMessage({
      message: '系统繁忙！',
      type: 'error',
      duration: 5 * 1000
    })
  }
  return Promise.reject(error)
})

export default service
